package com.example.demo.node;

/**
 * 环形链表1
 *
 * @author GXYH
 * @date 2021/08/13
 */
public class CycleListNode1 {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public boolean hasCycle(ListNode head) {
        //定义两个指针从头开始走
        ListNode fast = head;
        ListNode slow = head;
        //如果有下一项一直走
        while (fast != null && fast.next != null) {
            //fast一次走两步
            fast = fast.next.next;
            //slow一次一部
            slow = slow.next;
            //如果相遇，证明有环
            if (slow == fast) {
                return true;
            }
        }
        //有一人走完，则无环
        return false;
    }
}
